import 'dart:async';

import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_taotaoshipin/app/app_controller.dart';
import 'package:flutter_taotaoshipin/http/dao/ad_dao.dart';
import 'package:flutter_taotaoshipin/pages/drama_detail/episode/drama_episode_page.dart';
import 'package:flutter_taotaoshipin/pages/purchase/top/top_purchase_controller.dart';
import 'package:flutter_taotaoshipin/pages/purchase/top/top_purchase_page.dart';
import 'package:flutter_taotaoshipin/routes/app_routes.dart';
import 'package:flutter_taotaoshipin/value/global_config.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_taotaoshipin/http/dao/buy_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/drama_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/interact_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/user_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/video_dao.dart';
import 'package:flutter_taotaoshipin/model/buy_drama_pay_entity.dart';
import 'package:flutter_taotaoshipin/model/drama_interact_info_entity.dart';
import 'package:flutter_taotaoshipin/model/drama_list_entity.dart';
import 'package:flutter_taotaoshipin/model/drama_main_info_entity.dart';
import 'package:flutter_taotaoshipin/model/interact_user_collect_entity.dart';
import 'package:flutter_taotaoshipin/model/interact_user_collect_rm_entity.dart';
import 'package:flutter_taotaoshipin/model/interact_user_praise_entity.dart';
import 'package:flutter_taotaoshipin/model/interact_user_praise_rm_entity.dart';
import 'package:flutter_taotaoshipin/model/interact_user_share_entity.dart';
import 'package:flutter_taotaoshipin/model/user_drama_auth_list_entity.dart';
import 'package:flutter_taotaoshipin/model/video_geturl_entity.dart';
import 'package:flutter_taotaoshipin/player/flick_multi_manager.dart';
import 'package:flutter_taotaoshipin/util/format_utils.dart';
import 'package:get/get.dart';
import 'package:share_plus/share_plus.dart';

import 'drama_detail_state.dart';
import 'episode/drama_episode_controller.dart';

class DramaDetailController extends GetxController
    with GetSingleTickerProviderStateMixin {
  DramaDetailController({this.dramaId = 0, this.dramaTitle = ''});
  // 主剧id
  int dramaId;
  // 主剧名称
  String dramaTitle;

  final state = DramaDetailState();

  late PageController pageController;
  late FlickMultiManager flickMultiManager;
  late TabController tabController;

  // 当前集数
  int curSort = 0;
  int curListId = 0;

  int? isShowPayIndex;

  // 广告解锁集数
  int changeSort = 0;

  final methodChannel = const MethodChannel('hi_gromore');

  @override
  void onInit() {
    super.onInit();

    // 广告状态监听
    methodChannel.setMethodCallHandler((call) async {
      if (call.method == 'sendAdEcpm') {
        Map argus = call.arguments;
        AppController appController = Get.find();
        AdDao.eventCsj(
          appId: appController.csj.appId!,
          adverId: argus['adverId'],
          eventId: '2',
          ecpm: argus['ecpm'],
        );
      }
    });

    // 获取透传数据
    if (Get.arguments != null) {
      Map<String, dynamic> arguments = Get.arguments;
      dramaId = arguments['id'];
      dramaTitle = arguments['title'];

      state.pageIndex = (arguments['sort'] ?? 1) - 1;
      state.showBackBtn = true;
    } else {
      state.showBackBtn = false;
    }

    // 初始化page
    pageController = PageController(initialPage: state.pageIndex);
    // 初始化播放器
    flickMultiManager = FlickMultiManager();

    // 请求
    _loadFullData();

    // 获取签到详情
    _loadUserSignInDetailData();
    // 获取任务列表
    _loadUserTaskListData();
  }

  @override
  void onClose() {
    pageController.dispose();
    super.onClose();
  }

  void onPageChanged(int page) {
    state.pageIndex = page;
    update(['pageIndex']);
  }

  // void onPangrowthPlayletViewCreate(int id) {
  //   final String channelName = '${TtspPangrowthConstants.playletTypeId}/$id';
  //
  //   // 注册事件回调
  //   TtspPangrowthMethodChannelHandler.register(
  //     channelName,
  //     TtspPangrowthPlayletCallback(
  //       onProgress: (_) {},
  //       onStartPlay: (value) {
  //         print('穿山甲开始播放');
  //         state.pageIndex = value['episode'] - 1;
  //         update(['pageIndex']);
  //       },
  //       onContinue: (value) {
  //       },
  //       onPause: (_) {
  //       },
  //       onOverPlay: (value) {
  //         // 当前集数播放完成
  //       },
  //       onPlayCompletion: (value) {
  //         // 全部播放完成
  //       },
  //       isNeedBlock: (value) {
  //         print('请求播放');
  //         var pageIndex = value['episode'] - 1;
  //         fullLoadVideoUrlData(pageIndex, isCsj: true);
  //       },
  //     ),
  //   );
  // }

  Future<void> _loadFullData() async {
    // 获取主剧详情
    state.mainInfoEntity = await _loadMainInfoData();
    update(['mainInfoEntity']);
    // if (state.mainInfoEntity?.isSelf != 1) {
    //   pangrowth = TtspPangrowth();
    // }
    // 用户获取主剧列表权限
    state.userDramaAuthListEntityList = await _loadUserDramaAuthListData();
    // 获取主剧分集列表
    state.dramaListEntityList = await _loadDramaListData();
    update(['dramaListEntityList']);
    // 活动互动信息
    var entity = await _loadDramaInteractInfoData();
    if (entity != null) {
      state.dramaInteractInfoEntity = entity;
      update(['dramaInteractInfoEntity']);
    }
  }

  /// 获取主剧详情
  Future<DramaMainInfoEntity?> _loadMainInfoData() async {
    DramaMainInfoEntity? entity;
    try {
      var result = await DramaDao.getDramaMainInfo(dramaId, dramaTitle);
      if (result.code == 0) {
        entity = result.data;
      } else {
        if (result.message.isNotEmpty) {
          EasyLoading.showToast(result.message);
        }
      }
    } catch (_) {}
    return entity;
  }

  /// 获取分集列表数据
  Future<List<DramaListEntity>> _loadDramaListData() async {
    List<DramaListEntity> list = [];
    try {
      var result = await DramaDao.getDramaList(dramaId);
      if (result.code == 0) {
        if (result.data != null) {
          list = result.data!;
        }
      } else {
        if (result.message.isNotEmpty) {
          EasyLoading.showToast(result.message);
        }
      }
    } catch (_) {}
    return list;
  }

  /// 获取视频地址和视频信息
  Future<VideoGeturlEntity?> loadVideoUrlData(int dramaId, String vId) async {
    VideoGeturlEntity? entity;
    try {
      var result = await VideoDao.getUrl(
          dramaId: dramaId, vId: vId, isSelf: state.mainInfoEntity!.isSelf!);
      if (result.code == 0) {
        entity = result.data;
      } else {
        if (result.message.isNotEmpty) {
          EasyLoading.showToast(result.message);
        }
      }
    } catch (_) {}
    return entity;
  }

  /// 获取用户的分集观看权限列表
  Future<List<UserDramaAuthListEntity>> _loadUserDramaAuthListData() async {
    List<UserDramaAuthListEntity> list = [];
    try {
      var result = await UserDao.dramaAuthList(dramaId);
      if (result.code == 0) {
        if (result.data != null) {
          list = result.data!;
          list.sort((a, b) => a.sort!.compareTo(b.sort!));
          changeSort = list.last.sort! + 1;
        }
      } else {
        if (result.message.isNotEmpty) {
          EasyLoading.showToast(result.message);
        }
      }
    } catch (_) {}
    return list;
  }

  /// 剧集购买
  Future<BuyDramaPayEntity?> loadBuyDramaPayData(int dramaId) async {
    BuyDramaPayEntity? entity;
    try {
      var result = await BuyDao.dramaPay(dramaId);
      if (result.code == 0) {
        entity = result.data;
      } else {
        // if (result.message.isNotEmpty) {
        //   EasyLoading.showToast(result.message);
        // }
      }
    } catch (_) {}
    return entity;
  }

  /// 主剧交互信息
  Future<DramaInteractInfoEntity?> _loadDramaInteractInfoData() async {
    DramaInteractInfoEntity? entity;
    try {
      var result = await DramaDao.interactInfo(dramaId: dramaId);
      if (result.code == 0) {
        entity = result.data;
      } else {
        if (result.message.isNotEmpty) {
          EasyLoading.showToast(result.message);
        }
      }
    } catch (_) {
      EasyLoading.showError('网络错误');
    }
    return entity;
  }

  /// 点赞
  Future<InteractUserPraiseEntity?> loadPraiseData() async {
    InteractUserPraiseEntity? entity;
    try {
      var result = await InteractDao.userPraise(
          dramaId: dramaId, sort: curSort, listId: curListId);
      if (result.code == 0) {
        entity = result.data;
      } else {
        if (result.message.isNotEmpty) {
          EasyLoading.showToast(result.message);
        }
      }
    } catch (_) {
      EasyLoading.showError('网络错误');
    }
    return entity;
  }

  /// 取消点赞
  Future<InteractUserPraiseRmEntity?> loadPraiseRmData() async {
    InteractUserPraiseRmEntity? entity;
    try {
      var result = await InteractDao.userPraiseRm(
          dramaId: dramaId, sort: curSort, listId: curListId);
      if (result.code == 0) {
        entity = result.data;
      } else {
        if (result.message.isNotEmpty) {
          EasyLoading.showToast(result.message);
        }
      }
    } catch (_) {
      EasyLoading.showError('网络错误');
    }
    return entity;
  }

  /// 收藏
  Future<InteractUserCollectEntity?> loadCollectData() async {
    InteractUserCollectEntity? entity;
    try {
      var result = await InteractDao.userCollect(
          dramaId: dramaId, sort: curSort, listId: curListId);
      if (result.code == 0) {
        entity = result.data;
      } else {
        if (result.message.isNotEmpty) {
          EasyLoading.showToast(result.message);
        }
      }
    } catch (_) {
      EasyLoading.showError('网络错误');
    }
    return entity;
  }

  /// 取消收藏
  Future<InteractUserCollectRmEntity?> loadCollectRmData() async {
    InteractUserCollectRmEntity? entity;
    try {
      var result = await InteractDao.userCollectRm(
          dramaId: dramaId, sort: curSort, listId: curListId);
      if (result.code == 0) {
        entity = result.data;
      } else {
        if (result.message.isNotEmpty) {
          EasyLoading.showToast(result.message);
        }
      }
    } catch (_) {
      EasyLoading.showError('网络错误');
    }
    return entity;
  }

  /// 分享
  Future<InteractUserShareEntity?> loadShareData() async {
    InteractUserShareEntity? entity;
    try {
      var result = await InteractDao.userShare(
          dramaId: dramaId, sort: curSort, listId: curListId);
      if (result.code == 0) {
        entity = result.data;
      } else {
        if (result.message.isNotEmpty) {
          EasyLoading.showToast(result.message);
        }
      }
    } catch (_) {
      EasyLoading.showError('网络错误');
    }
    return entity;
  }

  bool showFuliRed() {
    bool hasSignIn = state.signInDetailEntity != null &&
            DateUtil.isToday(state.signInDetailEntity!.ctime! * 1000)
        ? true
        : false;
    bool hasDone =
        state.taskList.firstWhereOrNull((element) => element.state == 0) !=
            null;
    return !hasSignIn || !hasDone;
  }

  /// 检测付费，vip，金豆，广告，单剧购买
  bool checkNeedPay(int index) {
    // 为空
    if (state.dramaListEntityList.isEmpty) {
      return false;
    }

    var model = state.dramaListEntityList[index];
    var authIndex = state.userDramaAuthListEntityList
        .indexWhere((ele) => ele.id! == model.id!);
    return authIndex == -1;
  }

  /// 尝试扣费
  Future<bool> tryPayDrama(DramaListEntity model) async {
    var entity = await loadBuyDramaPayData(model.id!);
    if (entity != null) {
      if (entity.isBuy == true) {
        state.userDramaAuthListEntityList
            .add(UserDramaAuthListEntity()..id = model.id);
        return true;
      } else {
        // EasyLoading.showToast(entity.msg ?? '购买失败');
      }
    }
    return false;
  }

  /// 检查付费，尝试扣费，加载视频地址
  Future<VideoGeturlEntity?> fullLoadVideoUrlData(
    int index, {
    bool isCsj = false,
  }) async {
    var entity = state.dramaListEntityList[index];

    // 用户交互
    curSort = entity.sort!;
    curListId = entity.id!;

    // 检查付费
    if (checkNeedPay(index)) {
      // 1、支持vip
      if (state.mainInfoEntity?.canVipWatch == 1 && isVip()) {
        var res = await loadVideoUrlData(entity.id!, entity.vid!);
        if (isCsj) {
          // pangrowth?.allowToPlay(res != null);
        }
        return res;
      }

      // 2、金豆
      if (state.mainInfoEntity?.canCurPay == 1) {
        // 尝试购买
        var buy = await tryPayDrama(entity);
        if (buy) {
          // 更新授权列表
          state.userDramaAuthListEntityList =
              await _loadUserDramaAuthListData();
          update(['dramaListEntityList']);
          if (isCsj) {
            // var res = await loadVideoUrlData(entity.id!, entity.vid!);
            // pangrowth?.allowToPlay(res != null);
          }
          return null;
        }
      }

      // 3、广告
      AppController appController = Get.find();
      if (state.mainInfoEntity?.canAdPay == 1 &&
          appController.adDayLimit > appController.adTodayWatchCount) {
        // 是否正确的广告位
        var adver = appController.csj.list
            ?.firstWhereOrNull((element) => element.adverType == '0');
        if (adver != null && adver.adverId!.isNum) {
          var topCtl = Get.put(TopPurchaseController(
              mainInfoEntity: state.mainInfoEntity, sort: changeSort));
          var res = await Get.dialog(TopPurchasePage());
          if (res == 1) {
            // 内购成功
            if (isCsj) {
              fullLoadVideoUrlData(index, isCsj: true);
            } else {
              update(['dramaListEntityList']);
            }

            // 更新授权信息
            state.userDramaAuthListEntityList =
                await _loadUserDramaAuthListData();
          } else if (res == 2) {
            // 广告解锁
            if (isCsj) {
              // pangrowth?.setCurrentPlayletEpisode(changeSort);
            } else {
              if (changeSort == curSort) {
                update(['dramaListEntityList']);
              } else {
                pageController.jumpToPage(changeSort - 1);
              }
            }

            // 更新授权信息
            state.userDramaAuthListEntityList =
                await _loadUserDramaAuthListData();
          } else if (res == null && topCtl.adnName == 'gdt') {
            // 优量汇特殊处理
            if (isCsj) {
              // pangrowth?.setCurrentPlayletEpisode(changeSort);
            } else {
              if (changeSort == curSort) {
                update(['dramaListEntityList']);
              } else {
                pageController.jumpToPage(changeSort - 1);
              }
            }

            // 更新授权信息
            state.userDramaAuthListEntityList =
                await _loadUserDramaAuthListData();
          }

          return null;
        }
      }

      // 4、单剧
      // 弹窗
      if (isShowPayIndex != index) {
        var res = await Get.toNamed(AppRoutes.subscription,
            arguments: {'mainInfoEntity': state.mainInfoEntity});
        if (isCsj) {
          fullLoadVideoUrlData(index, isCsj: true);
        } else {
          update(['dramaListEntityList']);
        }

        // 更新授权信息
        state.userDramaAuthListEntityList = await _loadUserDramaAuthListData();
      }
      isShowPayIndex = index;
      return null;
    } else {
      isShowPayIndex = index;
      var res = await loadVideoUrlData(entity.id!, entity.vid!);
      if (isCsj) {
        // pangrowth?.allowToPlay(res != null);
      }
      return res;
    }
  }

  /// 点赞按钮
  void userPraiseBtnClicked() async {
    if (state.dramaInteractInfoEntity.praiseBool == true) {
      // 取消点赞
      var entity = await loadPraiseRmData();
      if (entity != null) {
        if (entity.state == 1) {
          state.dramaInteractInfoEntity.praise =
              _decrementCount(state.dramaInteractInfoEntity.praise);
          state.dramaInteractInfoEntity.praiseBool = false;
          update(['dramaInteractInfoEntity']);
        }
        if (entity.msg != null && entity.msg!.isNotEmpty) {
          EasyLoading.showToast(entity.msg!);
        }
      }
    } else {
      // 点赞
      var entity = await loadPraiseData();
      if (entity != null) {
        if (entity.state == 1) {
          state.dramaInteractInfoEntity.praise =
              _incrementCount(state.dramaInteractInfoEntity.praise);
          state.dramaInteractInfoEntity.praiseBool = true;
          update(['dramaInteractInfoEntity']);
        }
        if (entity.msg != null && entity.msg!.isNotEmpty) {
          EasyLoading.showToast(entity.msg!);
        }
      }
    }
  }

  /// 收藏按钮
  void userCollectBtnClicked() async {
    if (state.dramaInteractInfoEntity.collectBool == true) {
      // 取消收藏
      var entity = await loadCollectRmData();
      if (entity != null) {
        if (entity.state == 1) {
          state.dramaInteractInfoEntity.collect =
              _decrementCount(state.dramaInteractInfoEntity.collect);
          state.dramaInteractInfoEntity.collectBool = false;
          update(['dramaInteractInfoEntity']);
        }
        if (entity.msg != null && entity.msg!.isNotEmpty) {
          EasyLoading.showToast(entity.msg!);
        }
      }
    } else {
      // 收藏
      var entity = await loadCollectData();
      if (entity != null) {
        if (entity.state == 1) {
          state.dramaInteractInfoEntity.collect =
              _incrementCount(state.dramaInteractInfoEntity.collect);
          state.dramaInteractInfoEntity.collectBool = true;
          update(['dramaInteractInfoEntity']);
        }
        if (entity.msg != null && entity.msg!.isNotEmpty) {
          EasyLoading.showToast(entity.msg!);
        }
      }
    }
  }

  /// 分享按钮
  void userShareBtnClicked() async {
    var newText = GlobalConfig.systemShare;
    ShareResult result = await Share.shareWithResult(newText);
    if (result.status == ShareResultStatus.success) {
      var entity = await loadShareData();
      if (entity != null) {
        if (entity.state == 1) {
          state.dramaInteractInfoEntity.share =
              _incrementCount(state.dramaInteractInfoEntity.share);
          state.dramaInteractInfoEntity.shareBool = true;
          update(['dramaInteractInfoEntity']);
        }
        if (entity.msg != null && entity.msg!.isNotEmpty) {
          EasyLoading.showToast(entity.msg!);
        }
      }
    } else {
      EasyLoading.showToast('分享失败');
    }
  }

  // 分集按钮8
  void episodeButClicked() async {
    Get.put(
      DramaEpisodeController(
        mainInfoEntity: state.mainInfoEntity,
        dramaListEntityList: state.dramaListEntityList,
        userDramaAuthListEntityList: state.userDramaAuthListEntityList,
        isPlayingSort: curSort,
      ),
    );
    // 弹窗暂停播放
    flickMultiManager.pause();
    Map? map = await Get.bottomSheet(
      SizedBox(
        width: double.infinity,
        height: Get.mediaQuery.size.height * 0.5,
        child: const DramaEpisodePage(),
      ),
      isScrollControlled: true,
      persistent: false,
    );
    // 消失恢复播放
    flickMultiManager.play();
    if (map != null) {
      int page = map['index'];
      int sort = map['sort'];
      if (state.mainInfoEntity?.isSelf == 1) {
        // 获取真实页码数
        var realPage = state.dramaListEntityList
            .indexWhere((element) => element.sort == sort);
        pageController.jumpToPage(realPage);
      } else {
        // pangrowth?.setCurrentPlayletEpisode(page + 1);
      }
    }

  }

  int _incrementCount(int? count) {
    if (count == null) {
      return 0;
    } else {
      return count + 1;
    }
  }

  int _decrementCount(int? count) {
    if (count == null) {
      return 0;
    } else {
      return count - 1;
    }
  }

  /// 获取用户签到详情
  Future<void> _loadUserSignInDetailData() async {
    try {
      var result = await InteractDao.userSignInDetail();
      if (result.code == 0) {
        state.signInDetailEntity = result.data;
      }
    } catch (_) {}
  }

  /// 获取任务列表
  Future<void> _loadUserTaskListData() async {
    try {
      var result = await InteractDao.userTaskList();
      if (result.code == 0) {
        if (result.data != null) {
          if (GlobalConfig.isReview == 1) {
            state.taskList = result.data!
                .where((element) => !element.taskName!.contains('好评'))
                .toList();
          } else {
            state.taskList = result.data!;
          }
        } else {
          EasyLoading.showToast('数据为空');
        }
      } else {
        EasyLoading.showToast(result.message);
      }
    } catch (_) {}
  }

  void enterFullScreen() {
    flickMultiManager.fullScreen();
  }
}
